local curl = require "lcurl.safe"
local json = require "cjson.safe"

function request(url, header, method)--, para)
	pd.logInfo("request start")
	local data = ""
	local c = curl.easy{
		url = url,
		httpheader = header,
		ssl_verifyhost = 0,
		ssl_verifypeer = 0,
		timeout = 15,
		post = 1,
		--postfields = para,
		proxy = pd.getProxy(),
		writefunction = function(buffer)
			data = data .. buffer
			return #buffer
		end,
	}
	c:perform()
	c:close()
	--pd.logInfo(data)
	return string.gsub(data, "\\", "")
	
end

function urlEncode(s)
  s = string.gsub(s, "([^%w%.%- ])", function(c) return string.format("%%%02X", string.byte(c)) end)
  return string.gsub(s, " ", "+")
end



function name(szFullString)  
local nFindStartIndex = 1  
local nSplitIndex = 1  
local nSplitArray = {}  
while true do  
   local nFindLastIndex = string.find(szFullString, "/", nFindStartIndex)  
   if not nFindLastIndex then  
    nSplitArray[nSplitIndex] = string.sub(szFullString, nFindStartIndex, string.len(szFullString))  
    break  
   end  
   nSplitArray[nSplitIndex] = string.sub(szFullString, nFindStartIndex, nFindLastIndex - 1)  
   nFindStartIndex = nFindLastIndex + string.len("/")  
   nSplitIndex = nSplitIndex + 1  
end
local x = 1
while nSplitArray[x] ~= nil do
	x = x + 1
end
return nSplitArray[x-1]
end

script_info = {
	["title"] = "起飞~小飞机~嗖嗖~",
	["version"] = "0.0.1",
	["description"] = "#推荐#不支持黑号",
}

function onInitTask(task, user, file)

    if task:getType() ~= TASK_TYPE_BAIDU then
        return false
    end
    if user == nil then
        task:setError(-1, "用户未登录")
		return true
	end
	local appid = 778750
	if user:isSVIP() then
		appid = 250528
	end
	pd.logInfo(file.path)
	local url = "http://d.pcs.baidu.com/rest/2.0/pcs/file?app_id="..appid.."&method=locatedownload&path=" .. urlEncode(file.path)
	local header = {
	"User-Agent: netdisk;6.9.5.1;PC;PC-Windows;6.3.9600;WindowsBaiduYunGuanJia",
	"Cookie: " .. user:getCookie()
	}
	--"https://" + r.response.server[0] + r.response.path + "&filename=" + arr[0].server_filename
	local data = request(url, header, "GET")
	--pd.logInfo(data)
	data = json.decode(data)
	--pd.logInfo(data["path"])
	pd.logInfo("https://" .. data["server"][1] .. data["path"] .. "&filename=" .. urlEncode(name(file.path)))
	
    task:setUris("https://" .. data["server"][1] .. data["path"] .. "&filename=" .. urlEncode(name(file.path)))
    task:setOptions("user-agent", "netdisk;6.9.5.1;PC;PC-Windows;6.3.9600;WindowsBaiduYunGuanJia")
    task:setOptions("header", "Cookie: "..user:getCookie())
	task:setOptions("piece-length", "1M")
	task:setOptions("max-connection-per-server", "20")
    task:setOptions("allow-piece-length-change", "true")
	task:setOptions("split", "20")
	task:setIcon("icon/accelerate.png", "小飞机~嗖嗖~")
    return true
end

